<?php

namespace app\api\model;

class Product extends BaseModel
{
    protected $hidden = ['from', 'delete_time', 'update_time', 'head_img_id', 'topic_img_id', 'pivot', 'create_time', 'category_id', 'img_id'];

    //getUrlAttr,Url指的是数据库的字段名，可以指定任意字段名
    public function getMainImgUrlAttr($value, $data)
    {
        return $this->prefixImgUrl($value, $data);
    }

    //商品的详情图
    public function imgs()
    {
        return $this->hasMany('ProductImage', 'product_id', 'id');
    }

    //商品属性
    public function properties()
    {
        return $this->hasMany('ProductProperty', 'product_id', 'id');
    }

    public static function getMostRecent($count)
    {
        $produts = self::limit($count)->order('create_time desc')->select();
        return $produts;
    }

    public static function getProductsByCategoryID($categoryID)
    {
        $produts = self::where('category_id', '=', $categoryID)->select();
        return $produts;
    }

    public static function getProductDetail($id)
    {
        // $produt = self::with(['imgs.imgUrl']['properties'])->find($id);
        //使用$query闭包方法，关联img模型，进行条件查询
        $produt = self::with([
            'imgs' => function ($query) {
                $query->with(['imgUrl'])->order('order asc');
            }
        ])->with(['properties'])->find($id);
        return $produt;
    }
}
